package com.gz.thread.juc.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 */
public class CacheDemo {
    public static void main(String[] args) {
   //     MyCache cache = new MyCache();
        MyCacheLock cache = new MyCacheLock();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(()->{
                cache.push(String.valueOf(finalI),String.valueOf(finalI));
            }).start();
        }

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(()->{
                cache.get(String.valueOf(finalI));
            }).start();
        }
    }
}


class MyCache {
    private volatile Map<String, String> map = new HashMap<String, String>();

    public void push(String key, String value) {
        System.out.println("存入"+key);
        map.put(key, value);
    }

    public String get(String key) {
        System.out.println("获取"+key);
        return map.get(key);
    }
}

class MyCacheLock {
    private volatile Map<String, String> map = new HashMap<String, String>();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void push(String key, String value) {
        readWriteLock.writeLock().lock();
        System.out.println("存入"+key);
        map.put(key, value);
        readWriteLock.writeLock().unlock();
    }

    public String get(String key) {
        try {
            readWriteLock.readLock().lock();
            System.out.println("获取" + key);
            return map.get(key);
        }finally {
            readWriteLock.readLock().unlock();
        }
    }
}